package net.lovesrc.support.service.dama;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.kevinsawicki.http.HttpRequest;
import com.google.common.collect.Maps;
import com.zhouzhou.fastjava.BizException;
import com.zhouzhou.fastjava.util.ThreadKit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.InputStream;
import java.util.Map;


public class YunDaMaService implements DaMaService {

    private static final Logger logger = LoggerFactory.getLogger(YunDaMaService.class);

    // only jpg
    @Override
    public String recognise(String type, String contentType, InputStream is) {

        Map<String, Object> logParams = Maps.newHashMap();
        String body = HttpRequest
                .post("http://api.yundama.com/api.php?method=upload")
                .part("username", "zengjunbo")
                .part("password", "zjb314159")
                .part("codetype", type)
                .part("appid", "3480")
                .part("appkey", "0a24a10095cee90c559eb142e458ae9c")
                .part("timeout", "60")
                .part("file", (System.currentTimeMillis()) + ".jpg", contentType, is)
                .body();
        logParams.put("upload_res", body);
        logger.info(body);
        JSONObject jsonObj = JSON.parseObject(body);
        int ret = jsonObj.getIntValue("ret");
        if (ret == 0) {
            // success
            String cid = jsonObj.getString("cid");
            Map<String, Object> params = Maps.newHashMap();
            params.put("cid", cid);
            for (int i = 0; i < 20; i++) {
                String cidBody = HttpRequest.get("http://api.yundama.com/api.php?method=result", params, true).body();
                logger.info(cidBody);
                logParams.put("cid_res", cidBody);
                JSONObject cidJsonRoot = JSON.parseObject(cidBody);
                int cidRet = cidJsonRoot.getIntValue("ret");
                if (cidRet == 0) {
                    String text = cidJsonRoot.getString("text");
                    logParams.put("text", text);
                    return text;
                }
                if (cidRet == -3002) {
                    ThreadKit.sleepSeconds(1);
                    continue;
                }
                throw BizException.messageOf("GET_CID_ERROR");
            }
            throw BizException.messageOf("GET_CID_TIME_OUT");
        } else {
            // failure
            throw BizException.messageOf("UPDATE_VERIFY_IMAGE_ERROR");
        }
    }

}
